#include "CircList.h"

void createCircListR(CircList& first, CircList& rear, DataType A[], int n)
{
	first = (CircNode*)malloc(sizeof(CircNode));
	first->data = A[0];
	first->link = first;
	rear = first;
	CircNode* s;
	for (int i = 1; i < n; i++)
	{
		s = (CircNode*)malloc(sizeof(CircNode));
		s->data = A[i];
		s->link = rear->link;
		rear->link = s;
		rear = s;
	}
}

bool Insert(CircList& first, int i, DataType x)
{
	if (i < 1)
	{
		return false;
	}
	CircNode* p = first;
	CircNode* q;
	int k = 1;
	if (i == 1)
	{
		while (p->link != first)
		{
			p = p->link;
		}
	}
	else
	{
		while (p->link != first && k < i - 1)
		{
			p = p->link;
			k++;
		}
	}
	q = (CircNode*)malloc(sizeof(CircNode));
	q->data = x;
	q->link = p->link;
	p->link = q;
	if (i == 1)
	{
		first = q;
	}
	return true;
}

bool Remove(CircList& first, int i, DataType& x)
{
	if (i < 1)
	{
		return false;
	}
	CircNode* p = first;
	CircNode* q;
	int k = 1;
	if (i == 1)
	{
		while (p->link != first)
		{
			p = p->link;
		}
	}
	else
	{
		while (p->link != first && k < i - 1)
		{
			p = p->link;
			k++;
		}
		if (k < i - 1)
		{
			return false;
		}
	}
	q = p->link;
	p->link = q->link;
	x = q->data;
	free(q);
	if (i == 1)
	{
		first = p->link;
	}
	return true;
}

